package com.hgk.common.common.util;

import android.text.Editable;
import android.text.TextWatcher;
import android.widget.TextView;

public class TextWatcherUtil {
    public static boolean isChinese(char c) {
        Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
        if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
                || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION
                || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION
                || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) {
            return true;
        }
     
        return false;
    }
 
    public static int getChineseCount(String s) {
        int count = 0;
        char[] charArray = s.toCharArray();
        int size = charArray.length;
     
        for (int i = 0; i< size; ++i) {
            if (isChinese(charArray[i])) {
                ++count;
            }
        }
     
        return count;
    }

	public static class CustomTextWatcher implements TextWatcher {
	    private int mLimitLen;
	    private int mStart = 0;
	    private int mCount = 0;
	    private TextView mRemain = null;
	 
	    public CustomTextWatcher(int limitLen) {
	        mLimitLen = limitLen;
	    }
	 
	    public CustomTextWatcher(int limitLen, TextView remainText) {
	        mRemain = remainText;
	        mLimitLen = limitLen;
	        mRemain.setText(mLimitLen + "/" + mLimitLen);
	    }
	 
	    public void afterTextChanged(Editable s) {
	        int len = s.length();
//	        int chineseCount = TextWatcherUtil.getChineseCount(s.toString());
//	        int otherCount = (len - chineseCount) / 2;
//	        boolean isEvenOtherCount = ((len - chineseCount) % 2 == 0) ? true : false;
	     
//	        if (chineseCount + otherCount == mLimitLen) {
//	            if (!isEvenOtherCount) {
//	                s.delete(mStart, mCount + mStart);
//	                chineseCount = TextWatcherUtil.getChineseCount(s.toString());
//	                otherCount = (s.length() - chineseCount) / 2;
//	            }
//	        } else if (chineseCount + otherCount > mLimitLen) {
//	            s.delete(mStart, mCount + mStart);
//	            chineseCount = TextWatcherUtil.getChineseCount(s.toString());
//	            otherCount = (s.length() - chineseCount) / 2;
//	        }
	        
	        if (len > mLimitLen) {
	        	s.delete(mLimitLen, len);
	        } 
	     
	        if (mRemain != null) {
	            mRemain.setText(String.valueOf(mLimitLen - len < 0 ? 0 : (mLimitLen - len)) + "/" + mLimitLen);
	        }
	    }
	 
	    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
	        mStart = start;
	    }
	 
	    public void onTextChanged(CharSequence s, int start, int before, int count) {
	        mCount = count;
	    }
	}
}